#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <signal.h> 
#include <stdlib.h>       
#include <string.h>
#include <pthread.h>
//#include <sys/sem.h>
#include <errno.h>
#include <sys/ipc.h>
//#include <sys/msg.h>
#include <sys/timeb.h>
#include <sys/socket.h>
//#include <sys/socketvar.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <semaphore.h>
#include <string.h>
#include <termios.h>
#include <linux/input.h>
#include <semaphore.h>
#include <linux/shm.h>
#include <asm/unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include <mp4v2/mp4v2.h>
#include <swscale.h>


int initSws(void **sws,int srcW,int srcH, int dstW,int dstH)
{					 
		*sws = (void *)sws_getContext(srcW, srcH, AV_PIX_FMT_NV12, dstW, dstH, AV_PIX_FMT_NV12, 1, NULL, NULL, NULL);
		
		//printf("sws_getContext ok !\n");
		
		if(*sws == NULL)
		{
				return -1;	
		}	
		
		return 0;		
}

int swsScale(void *sws, unsigned char *src,int srcW, int srcH,unsigned char *dst,int dstW, int dstH)
{
		//printf("into swsScale\n");
		unsigned char* srcData[4];
		int srcStride[4];	
		
		unsigned char* dstData[4];
		int dstStride[4];		
		
		if( sws == NULL ) return -1;

		srcData[0]   = src;
		srcData[1]   = srcData[0] + srcW*srcH;
		srcData[2]   = srcData[1];
		srcData[3]   = 0;		
		srcStride[0] = srcW;
		srcStride[1] = srcW;
		srcStride[2] = srcW;
		srcStride[3] = 0;
		
		dstData[0]   = dst;
		dstData[1]   = dstData[0]  + dstW*dstH;
		dstData[2]   = dstData[1];
		dstData[3]   = 0;		
		dstStride[0] = dstW;
		dstStride[1] = dstW;
		dstStride[2] = dstW;
		dstStride[3] = 0;		
		
		//printf("before sws_scale\n");
		sws_scale(sws, (const unsigned char *const*)srcData, srcStride, 0, srcH, dstData, dstStride);
		//printf("after sws_scale\n");
		return 0;
} 


int delSws(void *sws)
{
		sws_freeContext((struct SwsContext *)sws);			
}

